package com.kaka.web_maven.dao;

import com.kaka.web_maven.entity.Users;

import java.sql.*;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
//    返回所有用户
    public List<Users> getList() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven",
                "root","");
        PreparedStatement pstmt = conn.prepareStatement("select * from user");
        ResultSet rs = pstmt.executeQuery();
        List<Users> list =new ArrayList<>() ;
        while(rs.next()){
            Users u = new Users();
            u.setId(rs.getInt("id"));
            u.setUsername(rs.getString("username"));
            u.setAge(rs.getInt("age"));
            u.setBirth(rs.getTimestamp("birth"));
            list.add(u);
        }
        System.out.println(list);
        rs.close();
        conn.close();
        return list;
    }
    public void save(Users user) {
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven?useUnicode=true&characterEncoding=utf8",
                    "root", "");
            String sql = "insert into user(username,age,birth) values(?,?,?)";
            PreparedStatement pstmt =  conn.prepareStatement(sql);
            pstmt.setString(1,user.getUsername());
            pstmt.setInt(2,user.getAge());
            pstmt.setObject(3,user.getBirth());
            pstmt.executeUpdate();
            conn.close();
            System.out.println("测试");
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}


